﻿
using System;
using System.Linq;
using System.Web.Mvc;
using ES.Models;

namespace ES.Controllers
{
    public class MyController : BaseController
    {


        [HttpGet]
        public ActionResult Login()
        {
            ViewBag.Title = "Giriş Yap";
            return View();
        }
        [HttpPost]
        public ActionResult Login(Customer customer)
        {

            if (ModelState.IsValid)
            {
                var cus = Db.Customers.SingleOrDefault(d => d.EmailAdress.Equals(customer.EmailAdress) &&
                    d.Password.Equals(customer.Password));
                if (cus != null)
                {
                    Session["loginkey"] = cus;
                    return RedirectToAction("Index", "Home");
                }
            }

            ViewBag.Title = "Giriş Yap";
            return View();
        }

        public ActionResult Index()
        {
            ViewBag.Title = "Sepetim";
            ViewBag.BasketProducts =
                Db.CustomerOfBaskets.Where(d => d.CustomerId == CurrentCustomer.id).Select(d => d.Product).ToList();
            ViewBag.Sales =
                Db.Sales.Where(d => d.CustomerId == CurrentCustomer.id).ToList();
            return View();
        }

        public ActionResult AddBasket(int? id)
        {
            if (id.HasValue)
            {

                if (!Db.CustomerOfBaskets.Any(d => d.ProductId == id && d.CustomerId == CurrentCustomer.id))
                {
                    var basketItem = new CustomerOfBasket
                      {

                          CustomerId = CurrentCustomer.id,
                          ProductId = id.Value
                      };
                    Db.CustomerOfBaskets.InsertOnSubmit(basketItem);
                    Db.SubmitChanges();
                }

            }
            Session["loginkey"] = Db.Customers.Single(d => d.id == CurrentCustomer.id);
            return RedirectToAction("Index");
        }

        public ActionResult RemoveBasket(int? id)
        {
            if (id.HasValue)
            {

                var basketItem = Db.CustomerOfBaskets.SingleOrDefault(d => d.ProductId == id &&
                    d.CustomerId == CurrentCustomer.id);

                if (basketItem != null) Db.CustomerOfBaskets.DeleteOnSubmit(basketItem);
                Db.SubmitChanges();
            }
            Session["loginkey"] = Db.Customers.Single(d => d.id == CurrentCustomer.id);
            return RedirectToAction("Index");
        }
    }
}
